package codebreaker.cliente.jogo.gui;


import codebreaker.cliente.Main;
import codebreaker.cliente.jogo.Historico;
import codebreaker.cliente.jogo.Jogo;
import codebreaker.cliente.jogo.JogoListener;
import codebreaker.cliente.sala.Sala;
import codebreaker.protocolo.Chute;
import codebreaker.protocolo.FimJogo;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author  Rodrigo
 */
public class GUIJogo extends javax.swing.JFrame implements JogoListener {
    
    private byte[] senha, senhaAdv;
    private String nomeAdv;
    
    private DefaultListModel historicoAdv, historico;
    
    /** Creates new form GUIJogo */
    public GUIJogo(String nomeAdv) {
	
	initComponents();
	
	this.nomeAdv = nomeAdv;
	
	this.setTitle(Main.jogador.getNome() + " x " + nomeAdv);
	
	/* cria dados */
	historico = new DefaultListModel();
	historicoAdv = new DefaultListModel();
	
	/* associa as listas */
	listSeus.setModel(historico);
	listAdv.setModel(historicoAdv);
	
	/* associa renderers */
	listSeus.setCellRenderer(new HistoricoRenderer());
	listAdv.setCellRenderer(new HistoricoRenderer());
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Código Gerado ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel4 = new javax.swing.JPanel();
        btnSendChute = new javax.swing.JButton();
        canvasChute = canvasChute = new CanvasSenha();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        areaChat = new javax.swing.JTextArea();
        messageChat = new javax.swing.JTextField();
        btnEnviar = new javax.swing.JButton();
        btnDesistir = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        canvasSenha = canvasSenha = new CanvasSenha(false);
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listAdv = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        listSeus = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setName("frameJogo");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Chute Atual"));
        btnSendChute.setText("Enviar Chute");
        btnSendChute.setEnabled(false);
        btnSendChute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendChuteActionPerformed(evt);
            }
        });

        canvasChute.setBackground(new java.awt.Color(255, 255, 255));

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(116, Short.MAX_VALUE)
                .add(btnSendChute)
                .addContainerGap())
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(canvasChute, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 219, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
                .add(canvasChute, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnSendChute)
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Chat"));
        areaChat.setColumns(20);
        areaChat.setEditable(false);
        areaChat.setRows(5);
        jScrollPane3.setViewportView(areaChat);

        btnEnviar.setText("Enviar");
        btnEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnviarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
                    .add(jPanel5Layout.createSequentialGroup()
                        .add(messageChat, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnEnviar)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 106, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(messageChat, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                    .add(btnEnviar)))
        );

        btnDesistir.setText("Desistir");
        btnDesistir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesistirActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Sua senha"));
        canvasSenha.setBackground(new java.awt.Color(255, 255, 255));

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(canvasSenha, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 225, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(canvasSenha, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(45, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Historico"));
        listAdv.setBorder(javax.swing.BorderFactory.createTitledBorder("Adversario"));
        jScrollPane1.setViewportView(listAdv);

        listSeus.setBorder(javax.swing.BorderFactory.createTitledBorder("Seus"));
        jScrollPane2.setViewportView(listSeus);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 232, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(20, 20, 20)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 232, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(6, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 184, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 184, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(btnDesistir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 135, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnDesistir)
                .add(13, 13, 13))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
	/* desiste */
	Main.sala.enviar(new FimJogo(FimJogo.DESISTENCIA));
	
	/* voltar pra sala de chat */
	Main.guiSala.setVisible(true);
	Main.sala.setJogoListener(null);
	this.dispose();
    }//GEN-LAST:event_formWindowClosed
    
    private void btnDesistirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDesistirActionPerformed
	Main.sala.enviar(new FimJogo(FimJogo.DESISTENCIA));
	
	/* voltar pra sala de chat */
	Main.guiSala.setVisible(true);
	Main.sala.setJogoListener(null);
	this.dispose();
    }//GEN-LAST:event_btnDesistirActionPerformed
    
    private void btnSendChuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendChuteActionPerformed
	
	byte[] chute = ((CanvasSenha)canvasChute).getSenha();
	
	/* compara */
	byte[] cmp = Jogo.comparar(chute, senhaAdv);
	
	/* envia senha */
	Main.sala.enviar(new Chute(chute));	
	
	/* verifica sua vitoria */
	if (cmp[0] == 4) {
	    JOptionPane.showMessageDialog(this,
		    "Parabens! voce venceu a partida. o seu chute e correto.",
		    "Jogo finalizado",
		    JOptionPane.INFORMATION_MESSAGE);
	    
	    /* envia fim jogo */
	    Main.sala.enviar(new FimJogo(FimJogo.VITORIA));
	    
	    /* voltar pra sala de chat */
	    Main.guiSala.setVisible(true);
	    Main.sala.setJogoListener(null);
	    this.dispose();
	    return;
	}
			
	/* adiciona informacao na lista */
	byte[] copia = new byte[4];
	copia[0] = chute[0]; copia[1] = chute[1]; 
	copia[2] = chute[2]; copia[3] = chute[3];
	historico.addElement(new Historico(copia, cmp[0], cmp[1]));
	
	/* mostra informacao */
	JOptionPane.showMessageDialog(this,
		cmp[0] + " dentro e " + cmp[1] + " fora.",
		"Chute",
		JOptionPane.INFORMATION_MESSAGE);
	
	/* aguarda receber chute de adversario */
	btnSendChute.setEnabled(false);
    }//GEN-LAST:event_btnSendChuteActionPerformed
    
    private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed
	if(!messageChat.getText().equals("")){
	    Main.sala.enviarChatPrivado(messageChat.getText());
	    areaChat.append("Eu: " + messageChat.getText() + "\n");
	    messageChat.setText("");
	}
    }//GEN-LAST:event_btnEnviarActionPerformed
    
    public void recebeuChat(String mensagem) {
	if (this.isVisible())
	    areaChat.append(nomeAdv + ": " + mensagem + "\n");
    }
    
    public void recebeuChute(byte[] chute) {
	
	if (senhaAdv == null) {
	    senhaAdv = chute;
	} else {
	    
	    /* compara */
	    byte[] cmp = Jogo.comparar(((CanvasSenha)canvasSenha).getSenha(), chute);
	    	    
	    /* verifica sua derrota */
	    if (cmp[0] == 4) {
		JOptionPane.showMessageDialog(this,
			nomeAdv + " acertou a sua senha. Voce perdeu!",
			"Jogo finalizado",
			JOptionPane.INFORMATION_MESSAGE);
		
		/* envia fim jogo */
		Main.sala.enviar(new FimJogo(FimJogo.DERROTA));
		
		/* voltar pra sala de chat */
		Main.guiSala.setVisible(true);
		Main.sala.setJogoListener(null);
		this.dispose();
		return;
	    }
	    
	    /* adiciona informacao na lista */
	    historicoAdv.addElement(new Historico(chute, cmp[0], cmp[1]));	    
	}
	
	/* agora vc pode chutar */
	btnSendChute.setEnabled(true);
    }
    
    public void fimJogo(byte motivo) {
	
	if (this.isVisible()) {
	    
	    if (motivo == FimJogo.DESISTENCIA)
		JOptionPane.showMessageDialog(this,
			nomeAdv + " desistiu deste jogo",
			"Jogo finalizado",
			JOptionPane.INFORMATION_MESSAGE);
	    
	    /* voltar pra sala de chat */
	    Main.guiSala.setVisible(true);
	    Main.sala.setJogoListener(null);
	    this.dispose();
	}
    }
    
    public void setSenha(byte[] senha) {
	this.senha = senha;
	((CanvasSenha)canvasSenha).setSenha(senha);
    }
    
    // Declaração de variáveis - não modifique//GEN-BEGIN:variables
    private javax.swing.JTextArea areaChat;
    private javax.swing.JButton btnDesistir;
    private javax.swing.JButton btnEnviar;
    private javax.swing.JButton btnSendChute;
    private java.awt.Canvas canvasChute;
    private java.awt.Canvas canvasSenha;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList listAdv;
    private javax.swing.JList listSeus;
    private javax.swing.JTextField messageChat;
    // Fim da declaração de variáveis//GEN-END:variables
    
}
